//
//  AppDelegate.m
//  NicePass
//
//  Created by fangzhengwei on 2017/6/27.
//  Copyright © 2017年 fangzhengwei. All rights reserved.
//

#import "AppDelegate.h"
#import <AMapFoundationKit/AMapFoundationKit.h>
#import "WBPopOverView.h"
#import <AFNetworkReachabilityManager.h>
// 引入JPush功能所需头文件
#import "JPUSHService.h"
// iOS10注册APNs所需头文件
#ifdef NSFoundationVersionNumber_iOS_9_x_Max
#import <UserNotifications/UserNotifications.h>
#endif
// 如果需要使用idfa功能所需要引入的头文件（可选）
#import <AdSupport/AdSupport.h>
#import <UMSocialCore/UMSocialCore.h>
#import <WXApi.h>
#import "NXYRechargeViewModel.h"
#import "HMGuideView.h"

static NSString *const kAppVersion = @"appVersion";

@interface AppDelegate ()<JPUSHRegisterDelegate,WXApiDelegate>

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    JPUSHRegisterEntity * entity = [[JPUSHRegisterEntity alloc] init];
    entity.types = JPAuthorizationOptionAlert|JPAuthorizationOptionBadge|JPAuthorizationOptionSound;

    [JPUSHService registerForRemoteNotificationConfig:entity delegate:self];

    [JPUSHService setupWithOption:launchOptions appKey:@"2f65c9077dcc65f9ca4ced59" channel:@"iOS"
                 apsForProduction:YES
            advertisingIdentifier:nil];

    NSDictionary *remoteNotification = [launchOptions objectForKey: UIApplicationLaunchOptionsRemoteNotificationKey];
    if (remoteNotification) {  // 点击消息进来的
       // 重置服务器端徽章
        [JPUSHService resetBadge];
    }
    
    [JPUSHService setBadge:0];
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
    //初始化沙盒模型,每次程序启动时都要清空模型
    
    [self configUSharePlatforms];
    
     // 创建window
    self.window = [[UIWindow alloc] init];
    [self switchRootVc];
    // 设置window的根控制器
    self.window.backgroundColor = [UIColor whiteColor];
    self.window.frame = [UIScreen mainScreen].bounds;
    // 显示window
    [self.window makeKeyAndVisible];
    
    return YES;
}


- (BOOL)isFirstLauch{
    //版本升级或首次登录
    NSUserDefaults *useDef = [NSUserDefaults standardUserDefaults];
    
    if (![useDef boolForKey:@"notFirst"]) {
        
        return YES;
        
    }else{
        
        return NO;
    }
}

- (void)switchRootVc{
    
    NXYUserAccountModel *userModel = [NXYUserAccountModel getUserAccountData];

    if (userModel.userId > 0) {
        
        NXYTabBarController *tabbar = [[NXYTabBarController alloc] init];
        self.window.rootViewController = tabbar;
    
    }else{
        
        NXYLoginNavController *loginNav = [[NXYLoginNavController alloc] init];
        
        if ([self isFirstLauch]) {
            
           [loginNav.view addSubview:[self addGuideView]];
        }
        self.window.rootViewController = loginNav;
    }

}

- (UIView *)addGuideView{
    
    HMGuideView *guideView = [[HMGuideView alloc] init];
    guideView.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
    [NXYRechargeViewModel getLaunchImage:^(NSArray *homeDataArr) {
        
        guideView.imageNames = homeDataArr;
    }];
    
    NSUserDefaults *useDef = [NSUserDefaults standardUserDefaults];
    // 保存用户数据
    [useDef setBool:YES forKey:@"notFirst"];
    
    return guideView;
}

- (void)configUSharePlatforms{
    
    [SVProgressHUD setDefaultStyle:SVProgressHUDStyleCustom];
    [SVProgressHUD setDefaultAnimationType:SVProgressHUDAnimationTypeNative]; //转的圈圈改为菊花
    [SVProgressHUD setForegroundColor:[UIColor blackColor]]; //字体颜色
    [SVProgressHUD setBackgroundColor:[UIColor colorWithRed:230 green:231 blue:238 alpha:1]];
    
    [NXYReleaseInfoModel clearModel];
    
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeRootVC:) name:changeRootVCNote object:nil];

    [AMapServices sharedServices].apiKey = @"4757293362a704775594b23170f702cd";
    [AMapServices sharedServices].enableHTTPS = YES;
    
    /* 设置友盟appkey */
    [[UMSocialManager defaultManager] setUmSocialAppkey:@"59b238cccae7e7436c000540"];
    
    [WXApi registerApp:@"wx4b6d5d6288da9211"];
    
    [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_WechatSession appKey:@"wx4b6d5d6288da9211" appSecret:@"5188093e61a4eca37b84bfdbf2bbae40" redirectURL:nil];
    [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_QQ appKey:@"1106349882"/*设置QQ平台的appID*/  appSecret:nil redirectURL:@"http://mobile.umeng.com/social"];
    
    [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_Sina appKey:@"904486868"  appSecret:@"8ee1e54dcb760b41a9fbc71907437486" redirectURL:@"https://sns.whalecloud.com/sina2/callback"];
}


// 支持所有iOS系统
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation{
    
    //6.3的新的API调用，是为了兼容国外平台(例如:新版facebookSDK,VK等)的调用[如果用6.2的api调用会没有回调],对国内平台没有影响
    BOOL result = [[UMSocialManager defaultManager] handleOpenURL:url sourceApplication:sourceApplication annotation:annotation];
    if (!result) {
        // 其他如支付等SDK的回调
        if ([url.host isEqualToString:@"safepay"]) {
            
            [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
                
//                NSLog(@"%@",resultDic);
            }];
        }
        
        return [WXApi handleOpenURL:url delegate:self];
    }
    
    return result;
}

//- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url{
//    
//    if ([url.host isEqualToString:@"safepay"]) {
//        
//        [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
//            
//            NSLog(@"%@",resultDic);
//        }];
//    }
//    
//    NSLog(@"%@",url);
//
//    return [WXApi handleOpenURL:url delegate:self];
//}
//
//- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options{
//    
//    if ([url.host isEqualToString:@"safepay"]) {
//        
//        [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
//            
//            NSLog(@"%@",resultDic);
//        }];
//    }
//
//    NSLog(@"%@",url);
//    
//    return [WXApi handleOpenURL:url delegate:self];
//}

//微信SDK自带的方法，处理从微信客户端完成操作后返回程序之后的回调方法,显示支付结果的
- (void)onResp:(BaseResp*)resp{
    
    //启动微信支付的response
    NSString *payResoult = [NSString stringWithFormat:@"errcode:%d", resp.errCode];
    
    if([resp isKindOfClass:[PayResp class]]){
        //支付返回结果，实际支付结果需要去微信服务器端查询
        switch (resp.errCode) {
            case 0:
                payResoult = @"支付结果：成功";
               
                [NXYRechargeViewModel refreshAccountLeaveMoney];
                
                break;
                
            case -1:
                payResoult = @"支付结果：失败";
                break;
                
            case -2:
                payResoult = @"用户已经退出支付";
                break;
                
            default:
                payResoult = [NSString stringWithFormat:@"支付结果：失败！retcode = %d, retstr = %@", resp.errCode,resp.errStr];
                break;
        }
    }
}


- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    /// Required - 注册 DeviceToken
    [JPUSHService registerDeviceToken:deviceToken];
}

- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    //Optional
//    NSLog(@"did Fail To Register For Remote Notifications With Error: %@", error);
}

#pragma mark- JPUSHRegisterDelegate

// iOS 10 Support
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(NSInteger))completionHandler {
    // Required
    NSDictionary * userInfo = notification.request.content.userInfo;
    
    NSDictionary *aps = [userInfo valueForKey:@"aps"];
    NSInteger badge = [[aps valueForKey:@"badge"] integerValue]; //badge数量
    //设置角标
    badge++;
    [JPUSHService setBadge:badge];
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:badge];
    
    if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
        
    }
    completionHandler(UNNotificationPresentationOptionAlert); // 需要执行这个方法，选择是否提醒用户，有Badge、Sound、Alert三种类型可以选择设置
}

// iOS 10 Support
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler {
    // Required
        NSDictionary * userInfo = response.notification.request.content.userInfo;
    
        NSDictionary *aps = [userInfo valueForKey:@"aps"];
        NSInteger badge = [[aps valueForKey:@"badge"] integerValue]; //badge数量
        //设置角标
        badge--;
        [JPUSHService setBadge:badge];
        [[UIApplication sharedApplication] setApplicationIconBadgeNumber:badge];
    
        if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
            
        [JPUSHService handleRemoteNotification:userInfo];
            
        [[NSNotificationCenter defaultCenter] postNotificationName:jpushToRefreshTabarAndBadgeNote object:nil];
            
        [[NSNotificationCenter defaultCenter] postNotificationName:jpushToRefreshTabarAndBadgeTwoNote object:nil];
    }
    completionHandler();  // 系统要求执行这个方法
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {

    // Required, iOS 7 Support
    [JPUSHService handleRemoteNotification:userInfo];
    completionHandler(UIBackgroundFetchResultNewData);
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {

    // Required,For systems with less than or equal to iOS6
    [JPUSHService handleRemoteNotification:userInfo];
}

- (void)changeRootVC:(NSNotification *)note{
    
    NSString *str = note.object;
    
    if ([str isEqualToString:@"Login"] || [str isEqualToString:@"Regist"]) {
        
        NXYTabBarController *tabbar = [[NXYTabBarController alloc] init];
        
        self.window.rootViewController = tabbar;
        
    }else if ([str isEqualToString:@"Mine"]){
        
        NXYLoginNavController *loginNav = [[NXYLoginNavController alloc] init];
        self.window.rootViewController = loginNav;
    }
    
}

- (void)dealloc{
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}


- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}


@end
